package com.hzpd.hainan.module.news.adapter;

import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * Created by xiaoqiu on 16/8/24.
 */
public class ListDataSetObserver extends DataSetObserver {
    private ListView listview;

    public ListDataSetObserver(ListView listview) {
        super();
        this.listview = listview;
    }

    @Override
    public void onChanged() {
        super.onChanged();
        setListViewHeightBasedOnChildren(listview);
    }

    /**
     * 计算listview高度并重设
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
